//
//  CenterMapViewController.m
//  51-Tour
//
//  Created by xiang ying on 14-3-19.
//  Copyright (c) 2014年 xiang ying. All rights reserved.
//

#import "CenterMapViewController.h"
#import "BMapKit.h"
#import "PKRevealController.h"
#import "TourMapViewController.h"
#import "ServiceManage.h"
#import "SVProgressHUD.h"
#import "NSString+TPCategory.h"


@interface CenterMapViewController ()<BMKMapViewDelegate,BMKSearchDelegate>{
    BMKMapView  *_mapView;
    BMKSearch   *maSearch;
    UILabel     *_tipLabel;
    
    BOOL        nearScenic;
    
    NSMutableArray *_mapAnnotaions;
    NSMutableArray *_removeAnnotations;
    
    
    BOOL        needLocate;
}

@end

@implementation CenterMapViewController

-(void)languageReset:(NSNotification *)noti{
    [self initNavigationItme:[[DataCenter instance] getStringForKey:@"AppName"]];
    
    if (_mapView.userLocation.coordinate.latitude!=0&&_mapView.userLocation.coordinate.longitude!=0) {
        //
        [ServiceManage getNearSceniceRequestInfo:@{@"LanKey":[[DataCenter instance] getLanguageType] == zh_cn?@"zh-cn":@"en-us",@"Lon":[NSString stringWithFormat:@"%f",_mapView.userLocation.location.coordinate.longitude],@"Lat":[NSString stringWithFormat:@"%f",_mapView.userLocation.location.coordinate.latitude]} completion:^(RespondDTO *respond) {
            [_mapAnnotaions removeAllObjects];
            if (respond.flag == respond_success) {
                NSLog(@"success");
                //地图添加标注
                [_mapAnnotaions addObjectsFromArray:respond.data];

                if (_mapView.delegate == self) {
                    if (_mapView.annotations.count!=0) {
                        [_removeAnnotations removeAllObjects];
                        [_removeAnnotations addObjectsFromArray:_mapView.annotations];
                        [_mapView removeAnnotations:_removeAnnotations];
                    }
                    [_mapView addAnnotations:_mapAnnotaions];
                }
                _tipLabel.text = [[DataCenter instance] getStringForKey:@"OutSideSuccess"];//[[DataCenter instance] getStringForKey:@"OutSideWaring"];
            }else{
                NSLog(@"no data");
                if (_mapView.annotations.count!=0) {
                    [_removeAnnotations removeAllObjects];
                    [_removeAnnotations addObjectsFromArray:_mapView.annotations];
                    [_mapView removeAnnotations:_removeAnnotations];
                }
                _tipLabel.text = [[DataCenter instance] getStringForKey:@"OutSideWaring"];
            }
        }];
    }else{
        nearScenic = NO;
    }
}

//override
- (void)initNavigationItme:(NSString *)title
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"topbar-bg_02"]];
    imageView.frame = CGRectMake(-8, 0, 320, 44);
    imageView.userInteractionEnabled = YES;
    [titleView addSubview:imageView];
    
    UIButton *leftbtn = [[UIButton alloc] initWithFrame: CGRectMake(0, 0, 44, 44)];
    [leftbtn setImage:[UIImage imageNamed:@"ic-list_02"] forState:UIControlStateNormal];
    [imageView addSubview:leftbtn];
    [leftbtn addTarget:self action:@selector(showLeft) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn = [[UIButton alloc] initWithFrame: CGRectMake(320-80, 0, 80, 44)];
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0,80-44,0,0)];
    [btn setImage:[UIImage imageNamed:@"ic-person_03"] forState:UIControlStateNormal];
    [imageView addSubview:btn];
    [btn addTarget:self action:@selector(showRight) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 7, 200, 35)];
    [titleLabel setText:title];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [titleLabel setTextColor:THEMECOLOR];
    titleLabel.backgroundColor = [UIColor clearColor];
    [imageView addSubview:titleLabel];
    
    self.navigationItem.titleView =  titleView;
}

- (void)showLeft{

    [[UIManagement shareInstance] showLeft];
}

- (void)showRight{
    [[UIManagement shareInstance] showRight];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = [[DataCenter instance] getStringForKey:@"AppName"];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(languageReset:) name:@"RESETLANGUAGE" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:@"applicationDidEnterBackground" object:nil];
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated {
    _mapView.frame = self.contentView.bounds;
    [self.contentView insertSubview:_mapView atIndex:0];
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    maSearch.delegate = self;
    
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    maSearch.delegate = nil;
}

- (void)viewDidAppear:(BOOL)animated{
    if (_mapView.annotations.count!=0) {
        [_removeAnnotations removeAllObjects];
        [_removeAnnotations addObjectsFromArray:_mapView.annotations];
        [_mapView removeAnnotations:_removeAnnotations];
    }
    if (_mapAnnotaions.count!=0) {
        [_mapView addAnnotations:_mapAnnotaions];
    }
    [_mapView setZoomLevel:14];
    needLocate = YES;
    [self performSelector:@selector(aimMap:) withObject:nil afterDelay:1];

//    if (_mapView.userLocation.location) {
//        [_mapView setCenterCoordinate:_mapView.userLocation.location.coordinate];
//    }
}

- (void)applicationDidEnterBackground:(NSNotification *)noti{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:@"applicationDidBecomeActive" object:nil];
}
//
- (void)applicationDidBecomeActive:(NSNotification *)noti{
    nearScenic = NO;
}

- (void)viewDidLoad
{
    [self initNavigationItme:[[DataCenter instance] getStringForKey:@"AppName"]];
    [super viewDidLoad];

    needLocate = YES;
    _mapAnnotaions = [NSMutableArray array];
    _removeAnnotations = [NSMutableArray array];
    
    _mapView = [[BMKMapView alloc] initWithFrame:self.contentView.bounds];
    _mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [self.contentView addSubview:_mapView];
    _mapView.delegate = self;
    _mapView.showsUserLocation = NO;
    _mapView.zoomLevel = 14;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.userLocation.title = nil;
    _mapView.showsUserLocation = YES;
    
    maSearch = [[BMKSearch alloc] init];
    maSearch.delegate = self;
    UIButton *locBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [locBtn setImage:[UIImage imageNamed:@"dw_25"] forState:UIControlStateNormal];
    [locBtn setImage:[UIImage imageNamed:@"dw-select_25"] forState:UIControlStateHighlighted];
    locBtn.frame = CGRectMake(8, self.contentView.bounds.size.height-60, 38, 38);
    [locBtn addTarget:self action:@selector(aimMap:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:locBtn];
    
    _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 21)];
    _tipLabel.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    _tipLabel.textColor = [UIColor whiteColor];
    _tipLabel.font = [UIFont systemFontOfSize:13];
    _tipLabel.text = @"";//[[DataCenter instance] getStringForKey:@"OutSideWaring"];
    [self.contentView addSubview:_tipLabel];
    nearScenic = NO;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - BMKMapViewDelegate
-(IBAction)aimMap:(id)sender{
    if (_mapView.userLocation.location) {
        [_mapView setCenterCoordinate:_mapView.userLocation.location.coordinate animated:YES]; 
    }
}

/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewWillStartLocatingUser:(BMKMapView *)mapView
{
	NSLog(@"start locate");
}

/**
 *用户位置更新后，会调用此函数
 *@param mapView 地图View
 *@param userLocation 新的用户位置
 */

- (void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation
{
	if (userLocation != nil) {
//		NSLog(@"%f %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
        if (needLocate) {
//            [_mapView setCenterCoordinate:_mapView.userLocation.location.coordinate];
            needLocate = NO;
        }

        if (!nearScenic) {
            nearScenic = YES;

            [ServiceManage getNearSceniceRequestInfo:@{@"LanKey":[[DataCenter instance] getLanguageType] == zh_cn?@"zh-cn":@"en-us",@"Lon":[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude],@"Lat":[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude]} completion:^(RespondDTO *respond) {
                [_mapAnnotaions removeAllObjects];
                if (respond.flag == respond_success) {
                    NSLog(@"search secnics success");
                    //地图添加标注
                    if (_mapView.annotations.count!=0) {
                        [_removeAnnotations removeAllObjects];
                        [_removeAnnotations addObjectsFromArray:_mapView.annotations];
                        [_mapView removeAnnotations:_removeAnnotations];
                    }
                    [_mapAnnotaions addObjectsFromArray:respond.data];
                    [_mapView addAnnotations:respond.data];
                    _tipLabel.text = [[DataCenter instance] getStringForKey:@"OutSideSuccess"];
                }else{
                    NSLog(@"no data");
                    if (_mapView.annotations.count!=0) {
                        [_removeAnnotations removeAllObjects];
                        [_removeAnnotations addObjectsFromArray:_mapView.annotations];
                        [_mapView removeAnnotations:_removeAnnotations];
                    }
                    _tipLabel.text = [[DataCenter instance] getStringForKey:@"OutSideWaring"];
                }
            }];
        }
    }
	
}
/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewDidStopLocatingUser:(BMKMapView *)mapView
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

// 根据anntation生成对应的View

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    NSString *AnnotationViewID = @"renameMark";
    BMKAnnotationView *newAnnotation = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (!newAnnotation) {
        newAnnotation = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        // 设置不可拖拽
        newAnnotation.draggable = NO;
//        newAnnotation.backgroundColor = [UIColor redColor];
//        CGPoint center = newAnnotation.center;
        [newAnnotation setFrame:CGRectMake(0, 0, 40, 54)];
        newAnnotation.backgroundColor = [UIColor clearColor];
//        newAnnotation.center = center;
//        newAnnotation.image = [UIImage imageNamed:@"map-location_05"];
        
        newAnnotation.paopaoView = nil;
        
        newAnnotation.exclusiveTouch = YES;
        newAnnotation.autoresizesSubviews = YES;
        newAnnotation.centerOffset = CGPointMake(0, -27);

//        UIImageView *left = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"icon_paopao_middle_left"] stretchableImageWithLeftCapWidth:10 topCapHeight:0]];
//        left.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleWidth;
//        left.frame = CGRectMake(0, 0, 20, 54);
//        
//        UIImageView *right = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"icon_paopao_middle_right"] stretchableImageWithLeftCapWidth:20 topCapHeight:0]];
//        right.frame = CGRectMake(20, 0, 20, 54);
//        right.autoresizingMask = UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleWidth;
//        [newAnnotation addSubview:left];
//        [newAnnotation addSubview:right];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 28)];
        label.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
        label.layer.borderWidth = 1;
        label.layer.cornerRadius = 4;
        label.layer.borderColor = BORDERCOLOR.CGColor;
        label.font  = [UIFont systemFontOfSize:15];
        label.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin;
        label.tag = 345;
        label.textAlignment = NSTextAlignmentCenter;
        [newAnnotation addSubview:label];
        
        UIImageView *papo = [[UIImageView alloc] initWithFrame:CGRectMake(10, label.frame.size.height+2, 20, 26)];
        papo.image = [UIImage imageNamed:@"map-location_05"];
        papo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
        [newAnnotation addSubview:papo];
    }
    [newAnnotation setAnnotation:annotation];

    UILabel *label = (UILabel*)[newAnnotation viewWithTag:345];
    label.text = annotation.title;
    CGFloat width = [annotation.title widthwithfont:label.font height:label.frame.size.height];
    newAnnotation.frame = CGRectMake(0, 0, width+6, newAnnotation.frame.size.height);

    return newAnnotation;
    
}

- (void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view{
    
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
    [mapView deselectAnnotation:view.annotation animated:YES];
    if (view.annotation!=mapView.userLocation) {
        if ([DataCenter instance].user) {
            TourMapViewController *tourMain = [[TourMapViewController alloc] initWithAnnotation:view.annotation mapView:mapView];
            [_removeAnnotations removeAllObjects];
            [_removeAnnotations addObjectsFromArray:_mapView.annotations];
            [_mapView removeAnnotations:_removeAnnotations];
            
            [self.navigationController pushViewController:tourMain animated:YES];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"]
                                                            message:[[DataCenter instance] getStringForKey:@"logintip"]
                                                           delegate:self
                                                  cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Cancel"]
                                                  otherButtonTitles:[[DataCenter instance] getStringForKey:@"Sure"], nil];
            [alert show];
        }
    }else{
//        [maSearch reverseGeocode:view.annotation.coordinate];
    }
}

// 当点击annotation view弹出的泡泡时，调用此接口
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view;
{
//    NSLog(@"paopaoclick");
//    if (view.annotation!=mapView.userLocation) {
//        if ([DataCenter instance].user) {
//            TourMapViewController *tourMain = [[TourMapViewController alloc] initWithAnnotation:view.annotation mapView:mapView];
//            [self.navigationController pushViewController:tourMain animated:YES];
//        }else{
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"[[DataCenter instance] getStringForKey:@"OutSideSuccess"]"]
//                                                            message:@"您还没登录,现在就去注册"
//                                                           delegate:self
//                                                  cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Cancel"]
//                                                  otherButtonTitles:[[DataCenter instance] getStringForKey:@"Sure"], nil];
//            [alert show];
//        }
//    }else{
//        [maSearch reverseGeocode:view.annotation.coordinate];
//    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [[UIManagement shareInstance] showRight];
    }
}

#pragma mark -
#pragma mark MASearchDelegate

- (void)onGetAddrResult:(BMKAddrInfo*)result errorCode:(int)error
{
	if (!error) {
        _mapView.userLocation.title = [NSString stringWithFormat:@"我在%@附近", result.strAddr];
	} else {
        NSLog(@"查询位置失败");
	}
}

@end
